package com.zhiyou100.controller;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.zhiyou100.mail.MailTest;
import com.zhiyou100.model.User;
import com.zhiyou100.service.UserService;
import com.zhiyou100.util.MD5Encryption;
import com.zhiyou100.validate.UserForget;
import com.zhiyou100.validate.UserLogin;
import com.zhiyou100.validate.UserRegister;

@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService us;
	
	@RequestMapping(value="/checkName",produces="text/html;charset=utf-8")
	@ResponseBody
	public String checkName(String username) {
		User user = us.selectUserByEmail(username);
		String mess = null;
		if(user==null) {
			mess = "用户名通过";
		}else{
			mess = "用户名已经被注册";
		}
		return mess;
	}
	
	@RequestMapping("/register")
	@ResponseBody
	public Map<String, Object> register(@Validated(value= {UserRegister.class}) User user,
							BindingResult res,
							HttpServletRequest request,
							String checkCode,HttpSession session) {
		
		boolean success = false;
		String message = "";
		Map<String,Object> result = new HashMap();
		
		String code = (String) session.getAttribute("validate");
		if(!code.equalsIgnoreCase(checkCode)) {
			message = "验证码不正确";
			result.put("success",success);
			result.put("message",message);
			return result;
		}
		
		if(res.hasErrors()) {
			List<FieldError> fds = res.getFieldErrors();
			for (FieldError fieldError : fds) {
				String name = fieldError.getField();
				String mess = fieldError.getDefaultMessage();
				
			}
			
		}else {
			String md5Pwd = "";
			
			try {
				md5Pwd = MD5Encryption.getEncryption(user.getPassword());
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			int i = us.insertUser(user.getEmail(),md5Pwd);
			
			if(i> 0) {
				success = true;
			}else {
				message = "用户名密码有误";	
			}
		}
		
		result.put("success",success);
		result.put("message",message);
		return result;
		
	}
	
	
	@RequestMapping("/home")
	public String home(HttpSession session,Model mo) {
		User user = (User) session.getAttribute("user");
		if(user==null) {
			return "/user/index";
		}
		User u = us.selectUserByEmail(user.getEmail());
		mo.addAttribute("user", u);
		return "/user/index";
	}
	@RequestMapping("/login")
	@ResponseBody
	public Map<String,Object> login(@Validated(value= {UserLogin.class}) User user,
						BindingResult res,String checkCode,
						Integer remember,HttpServletResponse response,
						HttpSession session,HttpServletRequest request) {
		
		boolean success = false;
		String message = "";
		Map<String,Object> result = new HashMap();
		
		//验证验证码是否正确
		String code = (String) session.getAttribute("validate");
		if(!code.equalsIgnoreCase(checkCode)) {
			message = "验证码不正确";
			result.put("success",success);
			result.put("message",message);
			return result;
		}
		
		//运用验证器判断用户名和密码是否输入有误
		if(res.hasErrors()) {
			List<FieldError> fds = res.getFieldErrors();
			for (FieldError fieldError : fds) {
				String name = fieldError.getField();
				String mess = fieldError.getDefaultMessage();
			}
			message = "用户名或者密码有误";
			result.put("success",success);
			result.put("message",message);
			return result;
		}
		
		User user1 = null;
		user1 = us.selectUserByEmail(user.getEmail());
		if(user1==null) {
			message = "账号不存在";
			result.put("success",success);
			result.put("message",message);
			return result;
		}
		try {
			user1 = us.checkUser(user.getEmail(), MD5Encryption.getEncryption(user.getPassword()));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(user1==null) {
			message = "用户名或者密码有误";
		}else {
			if(remember!=null) {
				Cookie uname = new Cookie("email", user.getEmail());
				Cookie upassword = new Cookie("password", user.getPassword());
				uname.setMaxAge(124545);
				upassword.setMaxAge(124545);
				uname.setPath("/maven_ssm_video");
				upassword.setPath("/maven_ssm_video");
				response.addCookie(uname);
				response.addCookie(upassword);
			}
			session.setAttribute("user", user);
			success = true;
		}
		result.put("success",success);
		result.put("message",message);
		return result;
	}
	@RequestMapping("/index")
	public String index(HttpSession session) {
		User user = (User) session.getAttribute("user");
		user = us.selectUserByEmail(user.getEmail());
		if(user!=null) {
			session.setAttribute("user", user);
		}
		return "index";
	}
	
	@RequestMapping("/forgetpwd")
	public String forgetpwd() {
		return "user/forget_pwd";
	}
	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		session.removeAttribute("user");
		return "redirect:/front/index.jsp";
	}
	
	@RequestMapping("/sendemail")
	@ResponseBody
	public Map<String, Object> sendemail(@Validated(value= {UserForget.class}) User user,BindingResult result,HttpSession session) {
		String message = "";
		boolean success = false;
		if(result.hasErrors()) {
			message = "邮箱有误，请重新输入";
		}else {
			User u = us.selectUserByEmail(user.getEmail());
			if(u!=null) {
				MailTest sendmail = new MailTest();
				try {
					sendmail.execute(user.getEmail(),session);
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				success = true;
			}else {
				message = "用户名不存在";
			}
		}
		Map<String, Object> map = new HashMap<>();
		map.put("message", message);
		map.put("success", success);
		return map;
	}
	
	@RequestMapping("/forget")
	public String forget(String email,String captcha,HttpSession session,Model mo) {
//		if(result.hasErrors()) {
//			List<FieldError> fds = result.getFieldErrors();
//			for (FieldError fieldError : fds) {
//				String name = fieldError.getField();
//				String mess = fieldError.getDefaultMessage();
//				mo.addAttribute(name, mess);
//				return "forward:/user/forgetpwd";
//			}
//		}
		String code = (String) session.getAttribute("checkCode");
		if(code==null) {
			return "forward:/user/forgetpwd";
		}else {
			if(!code.equalsIgnoreCase(captcha)) {
				mo.addAttribute("message", "验证码不正确");
				return "forward:/user/forgetpwd";
			}else {
				mo.addAttribute("email",email);
				mo.addAttribute("captcha", captcha);
				return "user/reset_pwd";
			}
		}
		
	}
	
	@RequestMapping("/resetpwd")
	public String resetpwd(String email,String captcha,String password,String pwdAgain,Model mo) {
		if(password!=pwdAgain) {
			mo.addAttribute("mess", "两次输入密码不正确");
		}else {
			try {
				String pass = MD5Encryption.getEncryption(password);
				int i = us.updateUserPassword(email, pass);
				if(i>0) {
					return "index";
					
				}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}
		return "user/reset_pwd";
	}
	
	@RequestMapping("/profile")
	public String profile(HttpSession session) {
		User user = (User) session.getAttribute("user");
		User u = us.selectUserByEmail(user.getEmail());
		session.setAttribute("user", u);
		return "user/profile";
	}
	@RequestMapping("/avatar")
	public String avatar(HttpSession session) {
		User user = (User) session.getAttribute("user");
		User u = us.selectUserByEmail(user.getEmail());
		session.setAttribute("user", u);
		return "user/avatar";
	}
	@RequestMapping("/password")
	public String password(HttpSession session) {
		User user = (User) session.getAttribute("user");
		User u = us.selectUserByEmail(user.getEmail());
		session.setAttribute("user", u);
		return "user/password";
	}
	
	@RequestMapping("/profile.do")
	public String updateProfile(HttpSession session,User user,Model mo) {
		if(user==null) {
			return "user/index";
		}
		System.out.println(user);
		User u = (User) session.getAttribute("user");
		u.setNick_name(user.getNick_name());
		u.setSex(user.getSex());
		u.setBirthday(user.getBirthday());
		u.setProvince(user.getProvince());
		u.setCity(user.getCity());
		int i = us.updateUser(u);
		if(i>0) {
			mo.addAttribute("user", u);
		}
		
		return "user/index";
	}
	
	@RequestMapping("/password.do")
	public String updatePassword(HttpSession session,String oldPassword,String newPassword,String newPasswordAgain) {
		
		if(newPassword!=null && newPasswordAgain!=null) {
			if(!newPassword.equals(newPasswordAgain)) {
				session.setAttribute("mess", "两次输入密码不统一");
				return "forward:/user/password";
			}
			
			User user = (User) session.getAttribute("user");
			String pass = "";
			try {
				pass = MD5Encryption.getEncryption(oldPassword);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			User u = us.checkUser(user.getEmail(), pass);
			if(u!=null) {
				try {
					pass = MD5Encryption.getEncryption(newPassword);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				int i = us.updateUserPassword(user.getEmail(), pass);
				if(i>0) {
					session.setAttribute("user", u);
				}
				return "user/index";
			}
			System.out.println(u);
			session.setAttribute("mess", "密码修改有误，请重新修改");
		}
		
		return "forward:/user/password";
	}
	private String setFileName(String filename) {
		String extension = FilenameUtils.getExtension(filename);
		String uuid = UUID.randomUUID().toString();
		return uuid+"."+extension;
	}
	
	private String getRealPath(String path,HttpServletRequest request) {
		String realPath=request.getServletContext().getRealPath(path);
		File file = new File(realPath);
		if(!file.exists()) {
			file.mkdirs();
		}
		return realPath;
	}
	@RequestMapping("/avatar.do")
	public String uploadHeadUrl(MultipartFile image_file,HttpServletRequest request) {
		if(image_file==null) {
			return "user/index";
		}
		User user = null;
		try {
			InputStream is = image_file.getInputStream();
			String path = this.getRealPath("/headImage", request);
			System.out.println(path);
			String name = image_file.getOriginalFilename();
	        
			String imageName = this.setFileName(name);
			File file = new File(path,imageName);
			OutputStream os = new FileOutputStream(file);
			IOUtils.copy(is, os);
			os.close();
			is.close();
			
			user = new User();
			user = (User) request.getSession().getAttribute("user");
			if(user.getHead_url()!=null&&user.getHead_url()!="") {
				file = new File(path,user.getHead_url());
				if(file.exists()) {
					file.delete();
				}
			}
			
			user.setEmail(user.getEmail());
			user.setHead_url(imageName);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		int i = us.updateUser(user);
		System.out.println("判断是否更新成功？");
		if(i>0) {
			System.out.println("更新成功");
			user = us.selectUserByEmail(user.getEmail());
			request.getSession().setAttribute("user", user);
		}
		return "user/index";
	}
}
